package com.milaidoo.fudong;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class HorizontalScrollContentView extends HorizontalScrollView implements BaseScrollView{

    private TextView tvContent;
    private RelativeLayout layout;
    private int scrollSpeed = 40;
    private int scrollTime = 300;
    private boolean isAutoScrolling;
    private int startPadding = 80;
    public HorizontalScrollContentView(Context context) {
        super(context);
    }

    public HorizontalScrollContentView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public HorizontalScrollContentView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public HorizontalScrollContentView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        Log.i("CustomScrollView", "scrollY:" + getScrollY() + " l" + l + " t" + t + "  oldl" + oldl + "  oldt" + oldt + "width = " + tvContent.getHeight() + 80);
//        if (getScrollX() == 0) {
//            //滚动到底部，ScrollView存在回弹效果效应
//            //优化，只过滤第一次
//            tvContent.post(new Runnable() {
//                @Override
//                public void run() {
//                    scrollTo((int) (textHeight + getWidth()),-startPadding);
//                }
//            });
//
//
//        }else if (layout.getMeasuredHeight() == (getScrollY() + getHeight())) {
//            //滚动到底部，ScrollView存在回弹效果效应
//            //优化，只过滤第一次
//            scrollTo(0,-startPadding);
//
//        }
    }

    @Override
    protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) {
        super.onOverScrolled(scrollX, scrollY, clampedX, clampedY);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        if(getHeight() <= 0){
            return;
        }
        updateLayout();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        Log.e("yqy","onFinishInflate  " + MeasureSpec.getSize(heightMeasureSpec));
    }

    public void updateLayout(){
        Log.e("YQY11","height = " + getHeight());
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) tvContent.getLayoutParams();
        params.setMargins(0,getHeight(),0,getHeight());
        tvContent.setLayoutParams(params);

    }

    private void initView(Context context){
        Log.e("yqy","initView  " + getHeight());
//        setScrollBarSize(0);
        setClipChildren(false);
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
        layout = new RelativeLayout(context);
        layout.setClipChildren(false);
//        layout.setGravity(Gravity.CENTER_VERTICAL);
        layout.setRotation(90);
        addView(layout,layoutParams);
        tvContent = new TextView(context);
        layout.addView(tvContent);
        initContentSize(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
    }
    int textWidth;
    public void initContentSize(final int width,final int height){
        final RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width,ViewGroup.LayoutParams.WRAP_CONTENT);
//        tvContent.setText("7个拦截器，5个自带的 独立线程：cleanupRunnable  清理空闲线程 添加的时候判断 cleanupRunnable线程是否在运行，没有则先天加cleanupRunnable 在添加要添加connection\n" +
//                "    addInterceptor(Interceptor)，这是由开发者设置的，会按照开发者的要求，在所有的拦截器处理之前进行最早的拦截处理，比如一些公共参数，Header都可以在这里添加。\n" +
//                "    RetryAndFollowUpInterceptor，这里会对连接做一些初始化工作，以及请求失败的充实工作，重定向的后续请求工作。跟他的名字一样，就是做重试工作还有一些连接跟踪工作。\n" +
//                "    BridgeInterceptor，这里会为用户构建一个能够进行网络访问的请求，同时后续工作将网络请求回来的响应Response转化为用户可用的Response，比如添加文件类型，content-length计算添加，gzip解包。\n" +
//                "    CacheInterceptor，这里主要是处理cache相关处理，会根据OkHttpClient对象的配置以及缓存策略对请求值进行缓存，而且如果本地有了可⽤的Cache，就可以在没有网络交互的情况下就返回缓存结果。\n" +
//                "    ConnectInterceptor，这里主要就是负责建立连接了，会建立TCP连接或者TLS连接，以及负责编码解码的HttpCodec\n" +
//                "    networkInterceptors，这里也是开发者自己设置的，所以本质上和第一个拦截器差不多，但是由于位置不同，所以用处也不同。这个位置添加的拦截器可以看到请求和响应的数据了，所以可以做一些网络调试。\n" +
//                "    CallServerInterceptor，这里就是进行网络数据的请求和响应了，也就是实际的网络I/O操作，通过socket读写数据。");
        tvContent.setLayoutParams(params);
//        tvContent.setPadding(0, startPadding,0,0);

        tvContent.post(new Runnable() {
            @Override
            public void run() {
                int vHeight = tvContent.getWidth();
                int numheight = tvContent.getLineCount();
                textHeight = (float) ((tvContent.getTextSize() + 0.00000007) / 0.7535);
//                Width = size(宽度和字体字号是相同的, 12sp字体, 单字宽为12dp)
                textHeight = numheight * textHeight + 1;
                if(numheight == 1){
                    //只有一行，需要偏移
                    textWidth = (int) tvContent.getPaint().measureText(tvContent.getText().toString());;
                }else{
                    textWidth = 0;
                }
                Log.e("YQY","---- " + vHeight + "    " + tvContent.getMeasuredHeight() + "===" +textHeight + "  numheight = " + numheight);
                ViewGroup.LayoutParams layoutParams = layout.getLayoutParams();
                layoutParams.width = (int) (textHeight + height * 2);
                layoutParams.height = (int) (textHeight + 2 * height);
                layout.setLayoutParams(layoutParams);
                Log.e("yqy","height = " + height + " wdith = " + width);

                RelativeLayout.LayoutParams textParams = (RelativeLayout.LayoutParams) tvContent.getLayoutParams();
                textParams.width = width;
                textParams.height = (int) (textHeight + 2 * height);
//                        new RelativeLayout.LayoutParams(width, (int) (textHeight + height + startPadding));
                textParams.setMargins(0,height,0,height);
                tvContent.setLayoutParams(textParams);
                if(textWidth > 0){
                    tvContent.setTranslationX((width - textWidth)/2);
                }
                post(new Runnable() {
                    @Override
                    public void run() {
                        scrollToStartPosition();
                    }
                });
            }
        });

    }

    private float textHeight;

    public void scrollToStartPosition(){
        Log.e("yqy","scrollToStartPosition = " + (layout.getHeight() -startPadding));
        scrollTo((int) (textHeight + 2 * tvContent.getWidth()),-startPadding);
        scrollBy(- startPadding,-startPadding);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public int dip2px(float dpValue) {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    private Handler handler = new Handler(Looper.getMainLooper());

    protected Runnable scrollRunnable = new Runnable() {
        @Override
        public void run() {
            // 获取此时刻 View的位置。
            int x = getScrollX();
            Log.e("yqy1111","x = " + x + "height = " + (tvContent.getHeight() + getHeight()));
            if(x <= scrollSpeed){
                scrollTo((int) (textHeight + getWidth()),-startPadding);
                handler.postDelayed(this,scrollTime);
                return;
            }
            scrollTo(getScrollX() - scrollSpeed,-startPadding);
            handler.postDelayed(this,scrollTime);
        }
    };

    @Override
    public void setText(String text) {
        tvContent.setText(text);
        initContentSize(screenWidth,screenHeight - dip2px(90));
    }

    @Override
    public void setTextSize(float textSize) {
        tvContent.setTextSize(textSize);
        initContentSize(screenWidth,screenHeight - dip2px(90));
    }

    @Override
    public void setScrollSpeed(int scrollSpeed) {
        this.scrollSpeed = scrollSpeed;
    }

    @Override
    public void setTextColor(int textColor) {
        tvContent.setTextColor(textColor);
    }

    @Override
    public void startAutoScroll() {
        isAutoScrolling = true;
        handler.removeCallbacksAndMessages(null);
        handler.postDelayed(scrollRunnable,0);
    }

    @Override
    public void stopAutoScroll() {
        isAutoScrolling = false;
        handler.removeCallbacksAndMessages(null);
    }

    @Override
    public String getText() {
        return tvContent.getText().toString();
    }

    @Override
    public float getTextSize() {
        return px2dip(tvContent.getTextSize());
    }

    @Override
    public int getScrollSpeed() {
        return scrollSpeed;
    }

    @Override
    public int getTextColor() {
        return tvContent.getTextColors().getDefaultColor();
    }

    @Override
    public boolean isAutoScrolling() {
        return isAutoScrolling;
    }

    private int screenWidth,screenHeight;
    @Override
    public void updateSize(int width, int height) {
//        updateLayout();
        this.screenWidth = width;
        this.screenHeight = height;
        initContentSize(width,height - dip2px(90));
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public int px2dip(float pxValue) {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
}
